import axios from "axios";
import { encrypt } from "./crypto.js";
import { baseURL, baseKjhURL, key, doublekey } from "./config.js";
import $messageBox from "@/components/componentTool/messageBox/index.js";
import $loginTip from "@/components/componentTool/loginTip/index.js";
import { getCookie, delCookie, getUser } from "@/assets/utils/tools.js";

// token的获取
function getStr(time, userid, logincode) {
  //验证字符串 兼容苹果机
  // return 'xstxwl.' + new Date(time.replace(/\-/g, "/")).getTime() + '.' + userid + '.' + logincode + '.txwl999';
  return "xstxwl." + time + "." + userid + "." + logincode + ".txwl999";
}
function getToken() {
  return new Promise((resolve, reject) => {
    axios.get(baseURL + "/api/Other/GetDate").then(
      (res) => {
        resolve(res.data.Data);
      },
      (err) => {
        console.log(err, "getDate_error");
        reject(null);
      }
    );
  });
}
export default (app) => {
  // 创建axios实例
  const service = axios.create({
    withCredentials: true, //是否允许携带cookie true携cookie false 不携带cookie
    baseURL: baseURL,
    timeout: 30000, // 请求超时时间,
  });

  // 添加响应拦截器
  service.interceptors.request.use(
    (config, response) => {
      //配置headers公共参数
      config.headers = {
        "Content-Type": "application/json;charset=utf-8",
        // 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      };

      //header添加用户信息
      let userObj = process.server
        ? getUser(app.$cookies.get("user"))
        : getCookie("user");
      // token
      return getToken()
        .then((res) => {
          config.headers.mtoken = encrypt(
            getStr(
              res,
              userObj ? userObj.LoginName : "",
              userObj ? userObj.LoginCode : ""
            ),
            key,
            doublekey
          );
          console.log(JSON.parse(config.headers) );
          return config;
        })
        .catch((err) => {
          return config;
        });
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  //返回状态判断
  // 成功 = 200
  // 错误提示 = 101
  // 异常 = 500
  // 无权限 = 501
  // 用户验证不通过 = 601
  // 登陆过期 = 602
  // 数据异常提示 = 603
  // 用户验证不通过(弹出登录) = 604
  // 余额不足 = 605
  service.interceptors.response.use(
    (res) => {
      let regStatus = /200/; //200 | 202 | 204
      if (!regStatus.test(res.status)) {
        if (process.client) {
          //客户端时
          //错误提示
          $messageBox({
            text: "网络错误，请稍后重试",
          });
        }
        console.log(
          "status",
          res.data,
          res.config.url,
          "mtoken:" + res.config.headers.mtoken
        );
        return Promise.reject(res.data);
      }

      //res.status 200 202  ， code状态不等于200的情况
      let code = res.data.Code ? res.data.Code : res.data.code;
      let message = res.data.Code ? res.data.Message : res.data.msg;
      let data = res.data.Code ? res.data.Data : res.data.body;
      //错误code返回
      if (code != 200) {
        console.log(
          "message",
          res.data,
          res.config.url,
          "mtoken:" + res.config.headers.mtoken
        );
        if (process.client) {
          //客户端时
          $messageBox({
            text: message,
          });
          let pathname = window.location.pathname.indexOf("userCenter");
          console.log(pathname, window.location.pathname);
          if (pathname == -1) {
            //非用户中心页面时的处理
            if (code == 604) {
              $loginTip({
                type: "登录失效,请重新登录",
              });
            }
            if (code == 605) {
              $messageBox({
                text: "余额不足，请充值",
              });
              setTimeout(() => {
                app.router.replace("/userCenter/recharge");
              }, 1500);
            }
          }
        }
        //登录过期
        if (code == 602 || code == 601 || code == 603) {
          //清除cookie 是用户中心页面则跳转登录
          let userObj = process.server
            ? getUser(app.$cookies.get("user"))
            : getCookie("user");
          if (process.client && userObj) {
            if (
              code == 602 ||
              code == 601 ||
              (code == 603 && data == "用户验证不通过")
            ) {
              app.store.commit("OUT_LOGIN");
              let pathname = window.location.pathname.indexOf("userCenter");
              console.log(pathname, "pathname", window.location.pathname);
              if (pathname !== -1) {
                app.router.replace("/login");
              } else {
                window.location.reload();
              }
            }
          }
        }

        return Promise.reject(res.data);
      }
      return Promise.resolve(data);
    },
    (error) => {
      const { config, code, message, response } = error;
      if (response) {
        console.log(
          "error",
          message,
          response.status,
          response.statusText,
          config.url
        );
      } else {
        console.log("err", error);
      }

      //客户端时
      if (process.client) {
        //错误提示
        $messageBox({
          text: "网络错误，请稍后重试",
        });
      }
      return Promise.reject(error);
    }
  );

  let fetch = function (method, url, params) {
    return new Promise((resolve, reject) => {
      service({
        method: method,
        url: url,
        params: method == "get" ? params : "",
        data: method == "post" ? params : "",
      })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  };

  return fetch;
};
